import 'dart:async';

import 'package:efood_multivendor/controller/cart_controller.dart';
import 'package:efood_multivendor/controller/category_controller.dart';
import 'package:efood_multivendor/controller/order_controller.dart';
import 'package:efood_multivendor/controller/product_controller.dart';
import 'package:efood_multivendor/controller/splash_controller.dart';
import 'package:efood_multivendor/data/model/response/cart_model.dart';
import 'package:efood_multivendor/data/model/response/order_details_model.dart';
import 'package:efood_multivendor/data/model/response/order_model.dart';
import 'package:efood_multivendor/data/model/response/product_model.dart';
import 'package:efood_multivendor/data/model/response/restaurant_model.dart';
import 'package:efood_multivendor/helper/date_converter.dart';
import 'package:efood_multivendor/helper/price_converter.dart';
import 'package:efood_multivendor/helper/route_helper.dart';
import 'package:efood_multivendor/helper/size_config.dart';
import 'package:efood_multivendor/util/dimensions.dart';
import 'package:efood_multivendor/util/styles.dart';
import 'package:efood_multivendor/view/base/custom_app_bar.dart';
import 'package:efood_multivendor/view/base/custom_button.dart';
import 'package:efood_multivendor/view/base/custom_image.dart';
import 'package:efood_multivendor/view/base/custom_non_gradient_button.dart';
import 'package:efood_multivendor/view/base/custom_snackbar.dart';
import 'package:efood_multivendor/view/screens/checkout/checkout_screen.dart';
import 'package:efood_multivendor/view/screens/order/widget/cancellation_reason_dialog.dart';
import 'package:efood_multivendor/view/screens/order/widget/order_product_widget.dart';
import 'package:efood_multivendor/view/screens/restaurant/restaurant_screen.dart';
import 'package:efood_multivendor/view/screens/review/rate_review_screen.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';

class OrderDetailsScreen extends StatefulWidget {
  final OrderModel? orderModel;
  final int orderId;
  final int? index;
  OrderDetailsScreen(
      {required this.orderModel, required this.orderId, this.index});

  @override
  _OrderDetailsScreenState createState() => _OrderDetailsScreenState();
}

class _OrderDetailsScreenState extends State<OrderDetailsScreen> {
  late StreamSubscription _stream;
  Restaurant? rest;
  CartController? cartController = Get.find<CartController>();
  OrderController? orderController;
  //OrderModel _order;
  //Restaurant restaurant;
  bool isActive = false;
  bool tooFar = true;
  bool isOpen = false;
  bool isactive = false;
  String? offDay;
  String? _deliveryServiceChargeType;
  double? _deliveryServiceChargeAmount = 0.0;
  double? _restaurantServiceChargeAmount = 0.0;
  Timer? _timer;
  DateTime? _orderCreatedAt;
  int? _timeRemaining;
  final int countdownDuration = 180;

  void _loadData(BuildContext context, bool reload) async {
    // restaurant = await Get.find<RestaurantController>().getRestaurantDetails(
    //     Restaurant(id: widget.orderModel.restaurant.id), 'order_details');
    // await Get.find<OrderController>().trackOrder(
    //     widget.orderId.toString(), reload ? null : widget.orderModel, false);
    if (widget.orderModel == null) {
      await Get.find<SplashController>().getConfigData();
    }
    Get.find<CategoryController>().getCategoryList(false);
    Get.find<OrderController>().getOrderDetails(widget.orderId.toString());
    orderController = Get.find<OrderController>();
    //_order = orderController.trackModel;
    // _deliveryServiceChargeType =
    //     Get.find<SplashController>().configModel?.deliveryServiceChargeType;
  }

  @override
  void initState() {
    super.initState();

    _stream = FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      _loadData(context, true);
    });

    _loadData(context, false);
  }

  @override
  void dispose() {
    super.dispose();
    _stream.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onHorizontalDragUpdate: (details) {
        int sensitivity = 12;
        if (details.delta.dx > sensitivity) {
          Get.back();
        } else if (details.delta.dx < -sensitivity) {}
      },
      child: WillPopScope(
        onWillPop: () async {
          if (widget.orderModel == null) {
            return Get.offAllNamed(RouteHelper.getInitialRoute("not found")) ==
                true;
          } else {
            return true;
          }
        },
        child: Scaffold(
          appBar: CustomAppBar(
              title: 'order_details'.tr,
              onBackPressed: () {
                if (widget.orderModel == null) {
                  Get.offAllNamed(RouteHelper.getInitialRoute("not found"));
                } else {
                  Get.back();
                }
              }),
          body: GetBuilder<OrderController>(builder: (orderController) {
            // double _deliveryCharge = 0;
            // double _itemsPrice = 0;
            // double _discount = 0;
            // double _couponDiscount = 0;
            // double _tax = 0;
            // double _totalServiceChargeAmount = 0;
            // double _addOns = 0;
            //  OrderModel _order = orderController.trackModel;
            List<Details> _orderDetailsList = [];
            List<int> _orderDetailsIdList = [];
            List<bool> _reviewed = [];
            bool deliveryManIsReviewed = false;
            bool everythingReviwed = false;
            bool foodReviewed = false;
            Future<Product> product;

            if (orderController.orderDetails != null &&
                orderController.orderDetails!.restaurant != null) {
              tooFar =
                  orderController.orderDetails!.restaurant!.too_far == true;
              isOpen =
                  orderController.orderDetails!.restaurant!.is_open == true;
              isactive =
                  orderController.orderDetails!.restaurant!.active == true;
              offDay = orderController.orderDetails!.restaurant!.offDay;
              if (orderController.orderDetails!.restaurant!.status == 1 &&
                  !tooFar &&
                  isOpen &&
                  offDay?.isNotEmpty != true) {
                isActive = true;
              }
            }

            if (orderController.orderDetails != null) {
              orderController.orderDetails!.details?.forEach((orderDetail) {
                if (!_orderDetailsIdList
                    .contains(orderDetail.foodDetails!.id!)) {
                  _orderDetailsList.add(orderDetail);
                  _orderDetailsIdList.add(orderDetail.foodDetails!.id!);
                }
              });
              // if (_order != null && _order.deliveryMan != null) {
              //   deliveryManIsReviewed = true;
              // }

              for (int index = 0;
                  index < (orderController.orderDetails?.details?.length ?? 0);
                  index++) {
                _reviewed.add(
                    orderController.orderDetails!.details![index].reviewed!);
              }

              if (orderController.orderDetails?.deliveryMan != null) {
                if (orderController.orderDetails!.deliveryMan!.reviewed ==
                        true &&
                    _reviewed.every((element) => element == true)) {
                  everythingReviwed = true;
                }
              } else if (_reviewed.every((element) => element == true) &&
                  orderController.orderDetails?.deliveryMan == null) {
                everythingReviwed = true;
              }

              if (_reviewed.every((element) => element == true)) {
                foodReviewed = true;
              }
            }

            if (orderController.orderDetails != null) {
              // _couponDiscount = _order.couponDiscountAmount;
              // _discount = _order.restaurantDiscountAmount;
              // _tax = _order.totalTaxAmount;
              // for (OrderDetailsModel orderDetails
              //     in orderController.orderDetails) {
              //   orderDetails.addOns.forEach((element) {});

              //   orderDetails.addOns.forEach((element) {
              //     _addOns = _addOns + (element.price * element.quantity);
              //   });
              //   _itemsPrice =
              //       _itemsPrice + (orderDetails.price * orderDetails.quantity);
              // }
            }

            return orderController.orderDetails != null
                ? Column(children: [
                    Expanded(
                        child: Scrollbar(
                            child: SingleChildScrollView(
                      physics: BouncingScrollPhysics(),
                      padding: EdgeInsets.all(Dimensions.PADDING_SIZE_SMALL),
                      child: Center(
                          child: SizedBox(
                              width: Dimensions.WEB_MAX_WIDTH,
                              child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Row(children: [
                                      Icon(Icons.watch_later, size: 17),
                                      SizedBox(
                                          width: Dimensions
                                              .PADDING_SIZE_EXTRA_SMALL),
                                      Text(
                                        DateConverter.dateTimeStringToDateTime(
                                            orderController
                                                    .orderDetails?.createdAt ??
                                                ''),
                                        style: sfRegular,
                                      ),
                                    ]),
                                    SizedBox(
                                        height: Dimensions.PADDING_SIZE_SMALL),
                                    orderController.orderDetails?.scheduled == 1
                                        ? Row(children: [
                                            Text('${'scheduled_at'.tr}:',
                                                style: sfRegular),
                                            SizedBox(
                                                width: Dimensions
                                                    .PADDING_SIZE_EXTRA_SMALL),
                                            Text(
                                                DateConverter
                                                    .dateTimeStringToDateTime(
                                                        orderController
                                                                .orderDetails
                                                                ?.scheduleAt ??
                                                            ''),
                                                style: sfMedium),
                                          ])
                                        : SizedBox(),
                                    SizedBox(
                                        height: orderController
                                                    .orderDetails?.scheduled ==
                                                1
                                            ? Dimensions.PADDING_SIZE_SMALL
                                            : 0),
                                    Get.find<SplashController>()
                                                .configModel
                                                ?.orderDeliveryVerification ==
                                            true
                                        ? Row(children: [
                                            Text(
                                                '${'delivery_verification_code'.tr}:',
                                                style: sfRegular),
                                            SizedBox(
                                                width: Dimensions
                                                    .PADDING_SIZE_EXTRA_SMALL),
                                            Text(
                                                orderController
                                                        .orderDetails?.otp ??
                                                    '',
                                                style: sfMedium),
                                          ])
                                        : SizedBox(),
                                    SizedBox(
                                        height: Get.find<SplashController>()
                                                    .configModel
                                                    ?.orderDeliveryVerification ==
                                                true
                                            ? 10
                                            : 0),
                                    Row(children: [
                                      Text(
                                          orderController.orderDetails
                                                  ?.orderType?.tr ??
                                              '',
                                          style: sfMedium),
                                      Expanded(child: SizedBox()),
                                      Container(
                                        padding: EdgeInsets.symmetric(
                                            horizontal:
                                                Dimensions.PADDING_SIZE_SMALL,
                                            vertical: Dimensions
                                                .PADDING_SIZE_EXTRA_SMALL),
                                        decoration: BoxDecoration(
                                          gradient: const LinearGradient(
                                              begin: Alignment.centerLeft,
                                              end: Alignment.centerRight,
                                              colors: [
                                                Color(0xffff8022),
                                                Color(0xffff2222)
                                              ]),
                                          borderRadius: BorderRadius.circular(
                                              Dimensions.RADIUS_SMALL),
                                        ),
                                        child: Text(
                                          orderController.orderDetails
                                                      ?.paymentMethod ==
                                                  'cash_on_delivery'
                                              ? 'cash_on_delivery'.tr
                                              : 'digital_payment'.tr,
                                          style: sfRegular.copyWith(
                                              color:
                                                  Theme.of(context).cardColor,
                                              fontSize: Dimensions
                                                  .fontSizeExtraSmall),
                                        ),
                                      ),
                                    ]),
                                    Divider(
                                        height: Dimensions.PADDING_SIZE_LARGE),
                                    Padding(
                                      padding: EdgeInsets.symmetric(
                                          vertical: Dimensions
                                              .PADDING_SIZE_EXTRA_SMALL),
                                      child: Row(children: [
                                        Text('${'item'.tr}:', style: sfRegular),
                                        SizedBox(
                                            width: Dimensions
                                                .PADDING_SIZE_EXTRA_SMALL),
                                        Text(
                                          orderController
                                                  .orderDetails?.details?.length
                                                  .toString() ??
                                              '',
                                          style: sfMedium.copyWith(
                                              color: Theme.of(context)
                                                  .primaryColor),
                                        ),
                                        Expanded(child: SizedBox()),
                                        Container(
                                            height: 7,
                                            width: 7,
                                            decoration: BoxDecoration(
                                              color: (orderController
                                                              .orderDetails
                                                              ?.orderStatus ==
                                                          'failed' ||
                                                      orderController
                                                              .orderDetails
                                                              ?.orderStatus ==
                                                          'refunded')
                                                  ? Colors.red
                                                  : Colors.green,
                                              shape: BoxShape.circle,
                                            )),
                                        SizedBox(
                                            width: Dimensions
                                                .PADDING_SIZE_EXTRA_SMALL),
                                        Text(
                                          orderController.orderDetails
                                                      ?.orderStatus ==
                                                  'delivered'
                                              ? '${'delivered_at'.tr} ${DateConverter.dateTimeStringToDateTime(orderController.orderDetails!.delivered!)}'
                                              : orderController.orderDetails
                                                      ?.orderStatus?.tr ??
                                                  '',
                                          style: sfRegular.copyWith(
                                              fontSize:
                                                  Dimensions.fontSizeSmall),
                                        ),
                                      ]),
                                    ),
                                    Divider(
                                        height: Dimensions.PADDING_SIZE_LARGE),
                                    orderController.orderDetails?.details
                                                ?.length ==
                                            1
                                        ? SizedBox(
                                            height:
                                                Dimensions.PADDING_SIZE_SMALL)
                                        : SizedBox(),
                                    orderController.orderDetails?.details
                                                ?.length ==
                                            1
                                        ? ListView.builder(
                                            shrinkWrap: true,
                                            physics:
                                                NeverScrollableScrollPhysics(),
                                            itemCount: orderController
                                                .orderDetails!.details!.length,
                                            itemBuilder: (context, index) {
                                              return OrderProductWidget(
                                                  details: orderController
                                                      .orderDetails!
                                                      .details![index]);
                                            },
                                          )
                                        : ExpansionTile(
                                            tilePadding:
                                                EdgeInsets.only(left: 0),
                                            title: Text(
                                              (orderController.orderDetails
                                                          ?.details?.length
                                                          .toString() ??
                                                      '') +
                                                  ' ' +
                                                  'item'.tr,
                                              style: sfMedium.copyWith(
                                                  fontSize:
                                                      Dimensions.fontSizeLarge *
                                                          1.3),
                                            ),
                                            subtitle: Text(
                                              PriceConverter.convertPrice(
                                                  orderController.orderDetails
                                                          ?.itemAmount
                                                          ?.toDouble() ??
                                                      0),
                                            ),
                                            leading: Stack(
                                              children: [
                                                ClipRRect(
                                                  borderRadius:
                                                      BorderRadius.circular(
                                                          Dimensions
                                                              .RADIUS_SMALL),
                                                  child: CustomImage(
                                                    image: orderController
                                                        .orderDetails!
                                                        .details![0]
                                                        .foodDetails!
                                                        .image!,
                                                    height: 65,
                                                    width: 70,
                                                    fit: BoxFit.cover,
                                                  ),
                                                ),
                                                Container(
                                                  height: 65,
                                                  width: 70,
                                                  decoration: BoxDecoration(
                                                    color: Colors.black
                                                        .withOpacity(0.7),
                                                    borderRadius:
                                                        BorderRadius.circular(
                                                            Dimensions
                                                                .RADIUS_SMALL),
                                                  ),
                                                  child: Center(
                                                      child: Text(
                                                    '${orderController.orderDetails?.details?.length ?? 0}',
                                                    style: sfMedium.copyWith(
                                                        fontSize: 19,
                                                        color: Colors.white),
                                                  )),
                                                ),
                                              ],
                                            ),
                                            children: [
                                                ListView.builder(
                                                    itemCount: orderController
                                                            .orderDetails
                                                            ?.details
                                                            ?.length ??
                                                        0,
                                                    shrinkWrap: true,
                                                    physics:
                                                        NeverScrollableScrollPhysics(),
                                                    itemBuilder: (ctx, index) {
                                                      return ListTile(
                                                        leading: ClipRRect(
                                                          borderRadius: BorderRadius
                                                              .circular(Dimensions
                                                                  .RADIUS_SMALL),
                                                          child: CustomImage(
                                                            image: orderController
                                                                .orderDetails!
                                                                .details![index]
                                                                .foodDetails!
                                                                .image!,
                                                            height: 65,
                                                            width: 70,
                                                            fit: BoxFit.cover,
                                                          ),
                                                        ),
                                                        title: Text(
                                                            orderController
                                                                    .orderDetails
                                                                    ?.details?[
                                                                        index]
                                                                    .foodDetails
                                                                    ?.name ??
                                                                ''),
                                                        subtitle: Text((orderController
                                                                    .orderDetails
                                                                    ?.details?[
                                                                        index]
                                                                    .quantity
                                                                    .toString() ??
                                                                '') +
                                                            " X " +
                                                            (orderController
                                                                    .orderDetails
                                                                    ?.details?[
                                                                        index]
                                                                    .foodDetails
                                                                    ?.price
                                                                    .toString() ??
                                                                '')),
                                                      );
                                                    })
                                              ]),
                                    (orderController.orderDetails?.orderNote !=
                                                null &&
                                            orderController.orderDetails
                                                    ?.orderNote?.isNotEmpty ==
                                                true)
                                        ? Column(
                                            crossAxisAlignment:
                                                CrossAxisAlignment.start,
                                            children: [
                                                Text('additional_note'.tr,
                                                    style: sfRegular),
                                                SizedBox(
                                                    height: Dimensions
                                                        .PADDING_SIZE_SMALL),
                                                Container(
                                                  width:
                                                      Dimensions.WEB_MAX_WIDTH,
                                                  padding: EdgeInsets.all(
                                                      Dimensions
                                                          .PADDING_SIZE_SMALL),
                                                  decoration: BoxDecoration(
                                                    borderRadius:
                                                        BorderRadius.circular(
                                                            Dimensions
                                                                .RADIUS_SMALL),
                                                    border: Border.all(
                                                        width: 1,
                                                        color: Theme.of(context)
                                                            .disabledColor),
                                                  ),
                                                  child: Text(
                                                    orderController.orderDetails
                                                            ?.orderNote ??
                                                        '',
                                                    style: sfRegular.copyWith(
                                                        fontSize: Dimensions
                                                            .fontSizeSmall,
                                                        color: Theme.of(context)
                                                            .disabledColor),
                                                  ),
                                                ),
                                                SizedBox(
                                                    height: Dimensions
                                                        .PADDING_SIZE_LARGE),
                                              ])
                                        : SizedBox(),
                                    Text('restaurant_details'.tr,
                                        style: sfRegular),
                                    SizedBox(
                                        height: Dimensions
                                            .PADDING_SIZE_EXTRA_SMALL),
                                    InkWell(
                                      onTap: () async {
                                        if (isActive && !tooFar) {
                                          Get.toNamed(
                                              RouteHelper.getRestaurantRoute(
                                                  orderController.orderDetails!
                                                      .restaurantId!),
                                              arguments: RestaurantScreen(
                                                  restaurant: orderController
                                                      .orderDetails!
                                                      .restaurant!));
                                        } else {
                                          showCustomSnackBar(
                                              'restaurant_is_not_available'.tr);
                                        }
                                      },
                                      child: Row(children: [
                                        ClipOval(
                                            child: CustomImage(
                                          image: orderController
                                              .orderDetails!.restaurant!.logo!,
                                          height: 35,
                                          width: 35,
                                          fit: BoxFit.cover,
                                        )),
                                        SizedBox(
                                            width:
                                                Dimensions.PADDING_SIZE_SMALL),
                                        Expanded(
                                            child: Column(
                                                crossAxisAlignment:
                                                    CrossAxisAlignment.start,
                                                children: [
                                              Text(
                                                orderController.orderDetails
                                                        ?.restaurant?.name ??
                                                    '',
                                                maxLines: 1,
                                                overflow: TextOverflow.ellipsis,
                                                style: sfRegular.copyWith(
                                                    fontSize: Dimensions
                                                        .fontSizeSmall),
                                              ),
                                              Text(
                                                orderController.orderDetails
                                                        ?.restaurant?.address
                                                        .toString() ??
                                                    '',
                                                maxLines: 1,
                                                overflow: TextOverflow.ellipsis,
                                                style: sfRegular.copyWith(
                                                    fontSize: Dimensions
                                                        .fontSizeSmall,
                                                    color: Theme.of(context)
                                                        .disabledColor),
                                              ),
                                            ])),
                                        (orderController
                                                        .orderDetails?.orderType ==
                                                    'take_away' &&
                                                (orderController
                                                            .orderDetails?.orderStatus ==
                                                        'pending' ||
                                                    orderController
                                                            .orderDetails?.orderStatus ==
                                                        'accepted' ||
                                                    orderController
                                                            .orderDetails?.orderStatus ==
                                                        'confirmed' ||
                                                    orderController.orderDetails
                                                            ?.orderStatus ==
                                                        'processing' ||
                                                    orderController.orderDetails
                                                            ?.orderStatus ==
                                                        'handover' ||
                                                    orderController.orderDetails
                                                            ?.orderStatus ==
                                                        'picked_up' ||
                                                    orderController.orderDetails
                                                            ?.orderStatus ==
                                                        'driver_arrived'))
                                            ? TextButton.icon(
                                                onPressed: () async {
                                                  String path =
                                                      'https://www.google.com/maps/dir/?api=1&destination=${orderController.orderDetails?.restaurant?.latitude}'
                                                      ',${orderController.orderDetails?.restaurant?.longitude}&mode=d';
                                                  final url = Uri.parse(path);
                                                  if (await canLaunchUrl(url)) {
                                                    await launchUrl(url);
                                                  } else {
                                                    showCustomSnackBar(
                                                        'unable_to_launch_google_map'
                                                            .tr);
                                                  }
                                                },
                                                icon: Icon(Icons.directions),
                                                label: Text('direction'.tr),
                                              )
                                            : SizedBox(),
                                      ]),
                                    ),
                                    SizedBox(
                                        height: Dimensions.PADDING_SIZE_LARGE),
                                    Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: [
                                          Text('item_price'.tr,
                                              style: sfRegular),
                                          Text(
                                              PriceConverter.convertPrice(
                                                  orderController.orderDetails
                                                          ?.itemAmount
                                                          ?.toDouble() ??
                                                      0),
                                              style: sfRegular),
                                        ]),
                                    SizedBox(height: 10),
                                    Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: [
                                          Text('addons'.tr, style: sfRegular),
                                          Text(
                                              '(+) ${PriceConverter.convertPrice(orderController.orderDetails?.addonAmount?.toDouble() ?? 0)}',
                                              style: sfRegular),
                                        ]),
                                    (orderController.orderDetails
                                                    ?.serviceCharge ??
                                                0) >
                                            0
                                        ? Column(
                                            children: [
                                              SizedBox(height: 10),
                                              Row(
                                                  mainAxisAlignment:
                                                      MainAxisAlignment
                                                          .spaceBetween,
                                                  children: [
                                                    Text('service_charge'.tr,
                                                        style: sfRegular),
                                                    Text(
                                                        '(+) ${orderController.orderDetails?.serviceCharge?.toStringAsFixed(2)} Br',
                                                        style: sfRegular),
                                                  ]),
                                            ],
                                          )
                                        : SizedBox(),
                                    Divider(
                                        thickness: 1,
                                        color: Theme.of(context)
                                            .hintColor
                                            .withOpacity(0.5)),
                                    Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: [
                                          Text('subtotal'.tr, style: sfMedium),
                                          Text(
                                              PriceConverter.convertPrice(
                                                  orderController.orderDetails
                                                          ?.subTotal
                                                          ?.toDouble() ??
                                                      0),
                                              style: sfMedium),
                                        ]),
                                    SizedBox(height: 10),
                                    Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: [
                                          Text('discount'.tr, style: sfRegular),
                                          Text(
                                              '(-) ${PriceConverter.convertPrice(orderController.orderDetails?.totalDiscountAmount?.toDouble() ?? 0)}',
                                              style: sfRegular),
                                        ]),
                                    SizedBox(height: 10),
                                    (orderController.orderDetails
                                                    ?.couponDiscountAmount ??
                                                0) >
                                            0
                                        ? Row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.spaceBetween,
                                            children: [
                                                Text('coupon_discount'.tr,
                                                    style: sfRegular),
                                                Text(
                                                  '(-) ${PriceConverter.convertPrice(orderController.orderDetails?.couponDiscountAmount?.toDouble() ?? 0)}',
                                                  style: sfRegular,
                                                ),
                                              ])
                                        : SizedBox(),
                                    SizedBox(
                                        height: (orderController.orderDetails
                                                        ?.couponDiscountAmount ??
                                                    0) >
                                                0
                                            ? 10
                                            : 0),
                                    Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: [
                                          Text('delivery_fee'.tr,
                                              style: sfRegular),
                                          (orderController.orderDetails
                                                          ?.deliveryCharge ??
                                                      0) >
                                                  0
                                              ? Text(
                                                  '(+) ${PriceConverter.convertPrice(orderController.orderDetails?.deliveryCharge?.toDouble() ?? 0)}',
                                                  style: sfRegular,
                                                )
                                              : Text('free'.tr,
                                                  style: sfRegular.copyWith(
                                                      color: Theme.of(context)
                                                          .primaryColor)),
                                        ]),
                                    Padding(
                                      padding: EdgeInsets.symmetric(
                                          vertical:
                                              Dimensions.PADDING_SIZE_SMALL),
                                      child: Divider(
                                          thickness: 1,
                                          color: Theme.of(context)
                                              .hintColor
                                              .withOpacity(0.5)),
                                    ),
                                    Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: [
                                          Text('total_amount'.tr,
                                              style: sfMedium.copyWith(
                                                fontSize:
                                                    Dimensions.fontSizeLarge,
                                                color: Theme.of(context)
                                                    .colorScheme
                                                    .secondary,
                                              )),
                                          Text(
                                            PriceConverter.convertPrice(
                                                orderController.orderDetails
                                                        ?.orderAmount
                                                        ?.toDouble() ??
                                                    0),
                                            style: sfMedium.copyWith(
                                                fontSize:
                                                    Dimensions.fontSizeLarge,
                                                color: Theme.of(context)
                                                    .colorScheme
                                                    .secondary),
                                          )
                                        ]),
                                    SizedBox(
                                      height: 25,
                                    ),
                                    (orderController.orderDetails?.bonusPoint ??
                                                0) >
                                            0
                                        ? Wrap(
                                            children: [
                                              Center(
                                                child: Text(
                                                  'bonus_message'.trParams({
                                                    'point': orderController
                                                            .orderDetails
                                                            ?.bonusPoint
                                                            .toString() ??
                                                        '',
                                                  }),
                                                  style: TextStyle(
                                                      fontSize: 17,
                                                      color: Theme.of(context)
                                                          .colorScheme
                                                          .secondary),
                                                ),
                                              ),
                                            ],
                                          )
                                        : SizedBox()
                                  ]))),
                    ))),
                    !orderController.showCancelled
                        ? Center(
                            child: SizedBox(
                              width: Dimensions.WEB_MAX_WIDTH,
                              child: Row(children: [
                                (orderController.orderDetails?.orderStatus ==
                                            'pending' ||
                                        orderController
                                                .orderDetails?.orderStatus ==
                                            'accepted' ||
                                        orderController
                                                .orderDetails?.orderStatus ==
                                            'confirmed' ||
                                        orderController
                                                .orderDetails?.orderStatus ==
                                            'processing' ||
                                        orderController
                                                .orderDetails?.orderStatus ==
                                            'handover' ||
                                        orderController
                                                .orderDetails?.orderStatus ==
                                            'picked_up' ||
                                        orderController
                                                .orderDetails?.orderStatus ==
                                            'driver_arrived')
                                    ? Expanded(
                                        child: CustomButton(
                                          buttonText: 'track_order'.tr,
                                          margin: EdgeInsets.all(
                                              Dimensions.PADDING_SIZE_SMALL),
                                          onPressed: () {
                                            Get.toNamed(RouteHelper
                                                .getOrderTrackingRoute(
                                                    orderController
                                                        .orderDetails!.id!,
                                                    false));
                                          },
                                        ),
                                      )
                                    : SizedBox(),
                                (orderController.orderDetails?.orderStatus ==
                                            'pending' ||
                                        orderController
                                                .orderDetails?.orderStatus ==
                                            'accepted' ||
                                        orderController
                                                .orderDetails?.orderStatus ==
                                            'confirmed' ||
                                        orderController
                                                .orderDetails?.orderStatus ==
                                            'processing' ||
                                        orderController
                                                .orderDetails?.orderStatus ==
                                            'handover' ||
                                        orderController
                                                .orderDetails?.orderStatus ==
                                            'driver_arrived')
                                    ? Expanded(
                                        child: Padding(
                                        padding: EdgeInsets.all(
                                            Dimensions.PADDING_SIZE_SMALL),
                                        child: TextButton(
                                          style: TextButton.styleFrom(
                                              minimumSize: Size(1, 50),
                                              shape: RoundedRectangleBorder(
                                                borderRadius:
                                                    BorderRadius.circular(
                                                        Dimensions
                                                            .RADIUS_SMALL),
                                                side: BorderSide(
                                                    width: 2,
                                                    color: Theme.of(context)
                                                        .disabledColor),
                                              )),
                                          onPressed: () {
                                            orderController.getTimerText(
                                                        widget.index ?? 0) !=
                                                    '0:00'
                                                ? showModalBottomSheet<dynamic>(
                                                    isScrollControlled: true,
                                                    shape:
                                                        RoundedRectangleBorder(
                                                      borderRadius: BorderRadius
                                                          .circular(Dimensions
                                                              .RADIUS_EXTRA_LARGE),
                                                    ),
                                                    context: context,
                                                    builder: (BuildContext bc) {
                                                      return Wrap(
                                                          children: <Widget>[
                                                            CancellationDialog(
                                                              orderId:
                                                                  orderController
                                                                      .orderDetails!
                                                                      .id!,
                                                              orderController:
                                                                  orderController,
                                                            ),
                                                          ]);
                                                    })
                                                : showAlertDialog();
                                          },
                                          child: Text(
                                              orderController.getTimerText(
                                                          widget.index ?? 0) ==
                                                      '0:00'
                                                  ? 'cancel_order'.tr
                                                  : '${"cancel".tr} (${orderController.getTimerText(widget.index ?? 0)})',
                                              style: sfBold.copyWith(
                                                color: Theme.of(context)
                                                    .disabledColor,
                                                fontSize:
                                                    Dimensions.fontSizeLarge,
                                              )),
                                        ),
                                      ))
                                    : SizedBox(),
                              ]),
                            ),
                          )
                        : Center(
                            child: Container(
                              width: Dimensions.WEB_MAX_WIDTH,
                              height: 50,
                              margin:
                                  EdgeInsets.all(Dimensions.PADDING_SIZE_SMALL),
                              alignment: Alignment.center,
                              decoration: BoxDecoration(
                                border: Border.all(
                                    width: 2,
                                    color: Theme.of(context).primaryColor),
                                borderRadius: BorderRadius.circular(
                                    Dimensions.RADIUS_SMALL),
                              ),
                              child: Text('order_cancelled'.tr,
                                  style: sfMedium.copyWith(
                                      color: Theme.of(context).primaryColor)),
                            ),
                          ),
                    (orderController.orderDetails?.orderStatus == 'delivered')
                        ? everythingReviwed == true
                            ? Center(
                                child: SizedBox(
                                  width: Dimensions.WEB_MAX_WIDTH,
                                  child: Row(children: [
                                    orderController.isProductDetailsLoading
                                        ? Expanded(
                                            child: Padding(
                                            padding: const EdgeInsets.all(8.0),
                                            child: CustomButton(
                                                buttonText: '',
                                                height: 15,
                                                width: 15,
                                                isLoading: true),
                                          ))
                                        : Expanded(
                                            child: CustomButton(
                                              buttonText: 'order_again'.tr,
                                              margin: EdgeInsets.all(Dimensions
                                                  .PADDING_SIZE_SMALL),
                                              onPressed: () async {
                                                if (Get.find<CartController>()
                                                            .cartRest[
                                                        orderController
                                                            .orderDetails
                                                            ?.restaurantId] !=
                                                    null) {
                                                  Get.find<CartController>()
                                                      .clearCartList(
                                                          resId: orderController
                                                              .orderDetails!
                                                              .restaurantId);
                                                }

                                                List<bool> _availableList = [];

                                                orderController
                                                    .startProductLoader();
                                                try {
                                                  await Future.forEach(
                                                      orderController
                                                          .orderDetails!
                                                          .details!,
                                                      (element) async {
                                                    Product? inputProduct;

                                                    for (var element
                                                        in orderController
                                                            .orderDetails!
                                                            .details!) {
                                                      inputProduct = Product(
                                                        id: element
                                                            .foodDetails!.id,
                                                        name: element
                                                            .foodDetails!.name,
                                                        description: element
                                                            .foodDetails!
                                                            .description,
                                                        image: element
                                                            .foodDetails!.image,
                                                        categoryId: element
                                                            .foodDetails!
                                                            .categoryId,
                                                        categoryIds: element
                                                            .foodDetails!
                                                            .categoryIds,
                                                        variations: element
                                                            .foodDetails!
                                                            .variations,
                                                        addOns: element
                                                            .foodDetails!
                                                            .addOns, // Assuming foodDetails has addOns
                                                        choiceOptions: element
                                                            .foodDetails!
                                                            .choiceOptions, // Assuming foodDetails has choiceOptions
                                                        price: element
                                                            .foodDetails!.price,
                                                        tax: element
                                                            .foodDetails!.tax,
                                                        discount: element
                                                            .foodDetails!
                                                            .discount,
                                                        discountType: element
                                                            .foodDetails!
                                                            .discountType,
                                                        availableTimeStarts: element
                                                            .foodDetails!
                                                            .availableTimeStarts,
                                                        availableTimeEnds: element
                                                            .foodDetails!
                                                            .availableTimeEnds,
                                                        restaurantId: element
                                                            .foodDetails!
                                                            .restaurantId,
                                                        restaurantName: element
                                                            .foodDetails!
                                                            .restaurantName,
                                                        restaurantDiscount: element
                                                            .foodDetails!
                                                            .restaurantDiscount,
                                                        restaurantOpeningTime:
                                                            element.foodDetails!
                                                                .restaurantOpeningTime,
                                                        restaurantClosingTime:
                                                            element.foodDetails!
                                                                .restaurantClosingTime,
                                                        scheduleOrder: element
                                                            .foodDetails!
                                                            .scheduleOrder,
                                                        avgRating: element
                                                            .foodDetails!
                                                            .avgRating,
                                                        ratingCount: element
                                                            .foodDetails
                                                            ?.ratingCount,
                                                        veg: element
                                                            .foodDetails?.veg,
                                                        restaurantTooFar: element
                                                            .foodDetails
                                                            ?.restaurantTooFar,
                                                        is_open: element
                                                            .foodDetails
                                                            ?.is_open,
                                                        is_alcohol: element
                                                            .foodDetails
                                                            ?.is_alcohol,
                                                        isHalal: element
                                                            .foodDetails
                                                            ?.isHalal,
                                                        discountedItemPrice: element
                                                            .foodDetails
                                                            ?.discountedItemPrice,
                                                      );

                                                      // Perform any async operation here if necessary
                                                    }

                                                    // You can now use inputProduct for further processing

                                                    Product? fetchedProduct =
                                                        await Get.find<
                                                                ProductController>()
                                                            .getProductDetails(
                                                                inputProduct!);

                                                    CartModel cart = CartModel(
                                                      fetchedProduct?.price,
                                                      fetchedProduct
                                                          ?.discountedItemPrice,
                                                      fetchedProduct
                                                          ?.variations,
                                                      fetchedProduct!.price! -
                                                          fetchedProduct
                                                              .discountedItemPrice!,
                                                      element.quantity,
                                                      [],
                                                      [],
                                                      element.itemCampaignId !=
                                                              null
                                                          ? true
                                                          : false,
                                                      fetchedProduct,
                                                      0,
                                                    );

                                                    cartController
                                                        ?.addToCart(cart);
                                                    cartController?.cartList
                                                        .forEach((cart) {
                                                      _availableList.add(cart
                                                              .product
                                                              ?.is_open ??
                                                          false);
                                                    });
                                                  });
                                                } catch (e) {
                                                  print(e.toString());
                                                } finally {
                                                  orderController
                                                      .stopProductLoader();
                                                }

                                                if (cartController
                                                        ?.cartList.isNotEmpty ==
                                                    true) {
                                                  if (_availableList
                                                      .contains(false)) {
                                                    showCustomSnackBar(
                                                        'one_or_more_product_unavailable'
                                                            .tr);
                                                  } else if (!isActive ||
                                                      tooFar) {
                                                    showCustomSnackBar(
                                                        'restaurant_is_not_available'
                                                            .tr);
                                                  } else {
                                                    Get.toNamed(
                                                        RouteHelper
                                                            .getCheckoutRoute(
                                                                'cart'),
                                                        arguments:
                                                            CheckoutScreen(
                                                          fromCart: true,
                                                          cartList: cartController
                                                                      ?.cartRest[
                                                                  orderController
                                                                      .orderDetails!
                                                                      .restaurantId] ??
                                                              [],
                                                          restaurantID:
                                                              orderController
                                                                  .orderDetails
                                                                  ?.restaurantId,
                                                          orderAgain: 1,
                                                        ));
                                                  }
                                                } else {
                                                  showCustomSnackBar(
                                                      'one_or_more_product_unavailable'
                                                          .tr);
                                                }
                                              },
                                            ),
                                          )
                                  ]),
                                ),
                              )
                            : Center(
                                child: SizedBox(
                                  width: Dimensions.WEB_MAX_WIDTH,
                                  child: Row(children: [
                                    Expanded(
                                      child: CustomNgButton(
                                        margin: EdgeInsets.all(
                                            Dimensions.PADDING_SIZE_SMALL),
                                        buttonText: 'review'.tr,
                                        onPressed: () {
                                          // List<Details> _orderDetailsList = [];
                                          // List<int> _orderDetailsIdList = [];
                                          // orderController.orderDetails.details
                                          //     .forEach((orderDetail) {
                                          //   if (!_orderDetailsIdList.contains(
                                          //       orderDetail.foodDetails.id)) {
                                          //     _orderDetailsList
                                          //         .add(orderDetail);
                                          //     _orderDetailsIdList.add(
                                          //         orderDetail.foodDetails.id);
                                          //   }
                                          // });
                                          Get.toNamed(
                                              RouteHelper.getReviewRoute(),
                                              arguments: RateReviewScreen(
                                                orderDetailsList:
                                                    orderController.orderDetails
                                                            ?.details ??
                                                        [],
                                                deliveryMan: orderController
                                                    .orderDetails?.deliveryMan,
                                                isFoodReviewed: foodReviewed,
                                                orderId: orderController
                                                    .orderDetails?.id
                                                    .toString(),
                                              ));
                                        },
                                      ),
                                    ),
                                    SizedBox(),
                                    orderController.isProductDetailsLoading
                                        ? Expanded(
                                            child: CustomButton(
                                                buttonText: '',
                                                height: 15,
                                                width: 15,
                                                isLoading: true))
                                        : Expanded(
                                            child: CustomButton(
                                              buttonText: 'order_again'.tr,
                                              margin: EdgeInsets.all(Dimensions
                                                  .PADDING_SIZE_SMALL),
                                              onPressed: () async {
                                                if (Get.find<CartController>()
                                                            .cartRest[
                                                        orderController
                                                            .orderDetails
                                                            ?.restaurantId] !=
                                                    null) {
                                                  Get.find<CartController>()
                                                      .clearCartList(
                                                          resId: orderController
                                                              .orderDetails!
                                                              .restaurantId);
                                                }

                                                List<bool> _availableList = [];
                                                orderController
                                                    .startProductLoader();
                                                await Future.forEach(
                                                    orderController.orderDetails
                                                            ?.details ??
                                                        [], (element) async {
                                                  Product? fetchedProduct =
                                                      await Get.find<
                                                              ProductController>()
                                                          .getProductDetails(
                                                              element
                                                                  .foodDetails);

                                                  CartModel cart = CartModel(
                                                    fetchedProduct?.price,
                                                    fetchedProduct?.discount,
                                                    fetchedProduct?.variations,
                                                    fetchedProduct?.discount,
                                                    element.quantity,
                                                    [],
                                                    [],
                                                    element.itemCampaignId !=
                                                            null
                                                        ? true
                                                        : false,
                                                    fetchedProduct,
                                                    0,
                                                  );

                                                  cartController
                                                      ?.addToCart(cart);
                                                  cartController?.cartList
                                                      .forEach((cart) {
                                                    _availableList.add(
                                                        cart.product?.is_open ==
                                                            true);
                                                  });
                                                });

                                                orderController
                                                    .stopProductLoader();

                                                if (cartController
                                                        ?.cartList.isNotEmpty ==
                                                    true) {
                                                  if (_availableList
                                                      .contains(false)) {
                                                    showCustomSnackBar(
                                                        'one_or_more_product_unavailable'
                                                            .tr);
                                                  } else if (!isActive ||
                                                      tooFar) {
                                                    showCustomSnackBar(
                                                        'restaurant_is_not_available'
                                                            .tr);
                                                  } else {
                                                    Get.toNamed(
                                                        RouteHelper
                                                            .getCheckoutRoute(
                                                                'cart'),
                                                        arguments:
                                                            CheckoutScreen(
                                                          fromCart: true,
                                                          cartList: cartController
                                                                      ?.cartRest[
                                                                  orderController
                                                                      .orderDetails
                                                                      ?.restaurantId] ??
                                                              [],
                                                          restaurantID:
                                                              orderController
                                                                  .orderDetails
                                                                  ?.restaurantId,
                                                          orderAgain: 1,
                                                        ));
                                                  }
                                                } else {
                                                  showCustomSnackBar(
                                                      'one_or_more_product_unavailable'
                                                          .tr);
                                                }
                                              },
                                            ),
                                          )
                                  ]),
                                ),
                              )
                        : SizedBox(),
                  ])
                : Center(
                    child: CircularProgressIndicator.adaptive(
                      backgroundColor: Theme.of(context).colorScheme.secondary,
                    ),
                  );
          }),
        ),
      ),
    );
  }

  void showAlertDialog() {
    AlertDialog alert3 = AlertDialog(
      scrollable: true,
      backgroundColor: Theme.of(context).cardColor,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(Dimensions.RADIUS_EXTRA_LARGE),
      ),
      title: Center(
          child: Column(
        children: [
          Icon(
            Icons.info,
            size: 50,
            color: Theme.of(context).primaryColor,
          )
        ],
      )),
      content: Container(
          width: 60.w,
          height: 7.h,
          padding: EdgeInsets.zero,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius:
                BorderRadius.circular(Dimensions.PADDING_SIZE_EXTRA_LARGE),
          ),
          child: Center(
              child: Text('cancel_time_over'.tr,
                  style: sfRegular.copyWith(fontSize: Dimensions.fontSizeLarge),
                  textAlign: TextAlign.center,
                  softWrap: true,
                  maxLines: 4))),
    );
    Get.dialog(alert3, barrierDismissible: true);
  }
}
